<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品原材料
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   create by allen.qiang
 * @version 1.0
 */

class goodsMater {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }
    
    /**
     * 查询商品原材料信息
     * @param $arg_array 参数数组
     * @return array|null
     */
    public function searchMater( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //原材料ID
        if (isset($arg_array['materID']) && is_numeric($arg_array['materID'])) {
            $sql .= ' AND materID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materID'];
        }
        
        //原材料名称
        if (isset($arg_array['materName']) && !empty($arg_array['materName'])) {
            $sql .= ' AND materName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['materName'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }
        
        //扩展
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
        	$sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_mater ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询原材料信息
            $search_sql = 'SELECT * FROM goods_mater ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'materID' => $item->materID,
                    'image' => G_IMAGE_URL . 'goods/' . $item->image,
                    'originalImage' => $item->image,
                    'materName' => $item->materName,
                    'sortOrder' => $item->sortOrder,
                    'useFlg' => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 获取原材料的最大序号
     */
	public function maxSort() {
		
		$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder) AS maxSort FROM goods_mater');
				
		$maxSort = $maxSort[0]->maxSort;
		
		return $maxSort;
		
	}
	
	/**
	 * 使用标志
	 */
	public function changeUse($materID,$useFlg) {
		
		try{
		
			//检测参数
			$goods_mater = new entity('goods_mater');
			$goods_mater->materID = $materID;
			if (!$this->dbca->fetch($goods_mater)) {
				throw new Exception( '查无此商品原材料信息' , 404 );
			}
		
			if (!is_numeric($useFlg) || !in_array($useFlg,array(0,1))) {
				throw new Exception( '使用状态不正确' , 404 );
			}
		
			//多页面操作问题
			if ($useFlg == 1 && $goods_mater->useFlg == 1) {
				throw new Exception( '商品原材料已经启用,请刷新页面' , 400 );
			}
		
			if ($useFlg == 0 && $goods_mater->useFlg == 0) {
				throw new Exception( '商品原材料已经禁用,请刷新页面' , 400 );
			}
		
			//使用状态修改
			$goods_mater->useFlg = $useFlg;
		
			if (!$this->dbca->save($goods_mater)) {
				throw new Exception( '使用状态修改失败' , 400 );
			}
		
			return array( 'code' => 200 , 'message' => 'ok' );
		
		} catch (Exception $e) {
		
			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500 , 'message' => '系统错误' );
			}
		
		}
		
	}
	
	/**
	 * 删除
	 */
	public function delgoodsMater($materID) {
		
		try{
		
			$this->dbca->beginTransaction();
		
			$goods_mater = new entity('goods_mater');
			$goods_mater->materID = $materID;
			if (!$this->dbca->fetch($goods_mater)) {
				throw new Exception('要删除的基本信息维度不存在',404);
			} else {
				if (!$this->dbca->delete($goods_mater)) {
					throw new Exception('删除基本信息维度失败',400);
				}
			}
		
			$this->dbca->commit();
		
			return array( 'code' => 200 , 'message' => 'ok' );
		
		} catch (Exception $e) {
		
			$this->dbca->rollback();
		
			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500 , 'message' => '系统错误' );
			}
		
		}
	}
	
	/**
	 * 保存、修改
	 */
	public function savegoodsMater($arg_array) {
		
		/**
    	 * 检查参数
    	 */
    	//定义错误变量
    	$error_msg = '';
    
    	if (isset($arg_array['materID']) && !empty($arg_array['materID'])) {
    		$materID = $arg_array['materID'];
    	} else {
    		$materID = 0;
    	}
    
    	if (isset($arg_array['materName']) && !empty($arg_array['materName'])) {
    		$materName = $arg_array['materName'];
    	} else {
    		$error_msg .= '未输入维度中文<br />';
    	}
    
    	if (isset($arg_array['sortOrder']) && is_numeric($arg_array['sortOrder']) > 0) {
    		$sortOrder = $arg_array['sortOrder'];
    	} else {
    		$error_msg .= '请输入正确的排序序号<br />';
    	}
    
    	if (isset($arg_array['hidImg']) && !empty($arg_array['hidImg'])) {
    		$image = $arg_array['hidImg'];
    	} else {
    		$error_msg .= '原材料图片未上传<br />';
    	}
    
    	if ($error_msg != '') {
    		return array( 'code' => 400 , 'message' => $error_msg );
    	}
    
    	/**
    	 * 数据存入数据库
    	 */
    	try{
    		global $G_PGLOB;
    
    		$this->dbca->beginTransaction();
    
    		//商品原材料数据
    		$goods_mater = new entity('goods_mater');
    		
    		$flg = 0;   //添加的标志
    
    		if ($materID > 0) {
    			$goods_mater->materID = $materID;
    			if (!$this->dbca->fetch($goods_mater)) {
                    throw new Exception('商品原材料不存在',400);
    			}
    			$flg = 1;   //修改的标志
                $allsortOrder = $this->dbca->stmt_query('SELECT sortOrder,materName FROM goods_mater WHERE materID != ?','i',$materID);
    		} else {
    			$goods_mater->creator = $G_PGLOB->currentUserID;
                $allsortOrder = $this->dbca->stmt_query('SELECT sortOrder,materName FROM goods_mater');
    		}

            $msg = '';
            foreach ($allsortOrder as $v) {
                if ($v->sortOrder == $sortOrder) {
                    $msg .= '排序序号已存在<br />';
                }
                if ($v->materName == $materName) {
                    $msg .= '维度中文已存在<br />';
                }
            }

            if (!empty($msg)) {
                throw new Exception($msg,400);
            }
    		
    		//截取图片名称
    		$imageName = substr($image, -23);
			copy(G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/kindeditor/'.date('Ymd').'/'.$imageName,G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/mater/'.$imageName);
    
    		$goods_mater->materName   	= $materName;
    		$goods_mater->image     	= 'mater/'.$imageName;
    		$goods_mater->sortOrder   	= $sortOrder;
    		$goods_mater->useFlg      	= 1;
    
    		if (!$this->dbca->save($goods_mater)) {
    			throw new Exception('商品原材料数据保存失败',400);
    		}
    
    		$this->dbca->commit();
    
    		return array( 'code' => 200 , 'message' => '数据保存成功' , 'data' => $flg );
    
    	} catch(Exception $e) {
    
    		$this->dbca->rollback();
    
    		if ($e->getCode() > 0) {
    			return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
    		} else {
    			error_log($e->getMessage());
    			return array( 'code' => 500 , 'message' => '系统错误' , 'data' => $flg );
    		}
    
    	}
	}
    
    /**
     * 查询商品和原材料信息映射关系
     * create by allen.qiang
     * @param $arg_array 参数数组
     * @return array|null
     */
    public function searchMaterRelation( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        //原材料ID
        if (isset($arg_array['materID']) && is_numeric($arg_array['materID'])) {
            $sql .= ' AND materID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materID'];
        }
        
        //扩展
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
        	$sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_mater_relation ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_mater_relation ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'postID' => $item->postID,
                    'materID' => $item->materID,
                    'materName' => $item->materName,
                    'image' => set_goods_img_link( $item->image ),
                    'orgitalImage' => $item->image,
                    'sortOrder' => $item->sortOrder
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

}